package com.modular.feign.custom;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.core.env.Environment;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class FeignUtil {
    public static Map<String, String> cache = new ConcurrentHashMap();

    public FeignUtil() {
    }

    public static String getRealUrl(Environment environment, String name) {
        String cacheUrl = (String)cache.get(name);
        if (StrUtil.isNotBlank(cacheUrl)) {
            return cacheUrl;
        } else {
            Integer port = (Integer) Convert.convert(Integer.class, environment.getProperty("mg-app." + name + ".port"));
            if (port == null) {
                throw ExceptionUtil.wrapRuntime("feign代理: " + name + " 未找到相应的端口配置");
            } else {
                String parentName = environment.getProperty("mg-app." + name + ".parent");
                if (StrUtil.isBlank(parentName)) {
                    throw ExceptionUtil.wrapRuntime("未配置当前服务: " + name + " 的父容器名称");
                } else {
                    String currentName = environment.getProperty("spring.application.name");
                    String host = parentName;
                    if (StrUtil.equals(parentName, currentName)) {
                        host = "127.0.0.1";
                    }

                    String url = "http://" + host + ":" + port;
                    cache.put(name, url);
                    return url;
                }
            }
        }
    }
}
